package org.example.projecttwo.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.example.projecttwo.common.Result;
import org.example.projecttwo.entity.Message;
import org.example.projecttwo.service.Imessage.IMessageRedisService;
import org.example.projecttwo.service.Imessage.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/message")
@Tag(name = "消息管理", description = "消息信息管理")

public class MessageController {

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IMessageRedisService mRedisService;

    @GetMapping("/list")
    @Operation(summary = "分页获取消息列表", description = "分页获取消息列表，支持状态筛选、接收范围筛选 -- 消息管理")
    public Result<IPage<Message>> listMessages(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer targetScope,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<Message> page = new Page<>(current, size);
        IPage<Message> result = messageService.pageBy(page, status, targetScope, keyword, startTime, endTime);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取消息详情", description = "根据消息ID获取消息详情 -- 消息管理")
    public Result<Message> getMessage(@PathVariable Long id) {
        Message message = messageService.getById(id);
        return Result.success(message);
    }

    @PostMapping
    @Operation(summary = "发布消息", description = "发布新消息 -- 消息管理")
    public Result<Message> createMessage(@Valid @RequestBody Message message) {
        if (message.getNoticeType() == null) {
            return Result.error("请选择通知形式");
        }
        message.setStatus(0);
        messageService.save(message);

        //如果设置了过期时间，存储到Redis（添加异常处理）
        if (message.getExpireTime() != null) {
            try {
                //转换为毫秒级时间戳
                long expireTime = message.getExpireTime().atZone(java.time.ZoneId.systemDefault())
                        .toInstant().toEpochMilli();
                mRedisService.setMessageExpiry(message.getId(), expireTime);
            } catch (Exception e) {
                // Redis连接失败时记录日志但不中断主流程
                System.err.println("Redis连接失败，消息过期功能暂时不可用: " + e.getMessage());
                // 可以选择将消息存储到数据库作为备选方案
            }
        }
        return Result.success(message);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除消息", description = "根据消息ID删除消息 -- 消息管理")
    public Result<String> deleteMessage(@PathVariable Long id) {
        messageService.removeById(id);

        //从Redis中移除该消息的过期时间（添加异常处理）
        try {
            mRedisService.removeMessageExpiry(id);
        } catch (Exception e) {
            System.err.println("Redis连接失败，无法移除消息过期记录: " + e.getMessage());
        }
        return Result.success("删除成功");
    }

    @PutMapping("/{id}/expire")
    @Operation(summary = "立即过期消息", description = "将消息状态设置为已过期 -- 消息管理")
    public Result<String> expireMessage(@PathVariable Long id) {
        messageService.updateStatus(id, 1);

        //从Redis中移除该消息的过期时间（添加异常处理）
        try {
            mRedisService.removeMessageExpiry(id);
        } catch (Exception e) {
            System.err.println("Redis连接失败，无法移除消息过期记录: " + e.getMessage());
        }
        return Result.success("已过期");
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除消息", description = "批量删除消息 -- 消息管理")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条消息");
        }
        messageService.removeByIds(ids);

        // 从Redis中移除这些消息的过期时间（添加异常处理）
        try {
            mRedisService.batchRemoveMessageExpiry(ids);
        } catch (Exception e) {
            System.err.println("Redis连接失败，无法批量移除消息过期记录: " + e.getMessage());
        }
        return Result.success("批量删除成功,共" + ids.size() + "条");
    }

    @PostMapping("/batch-expire")
    @Operation(summary = "批量立即过期消息", description = "批量将消息状态设置为已过期 -- 消息管理")
    public Result<String> batchExpire(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条消息");
        }
        messageService.batchUpdateStatus(ids, 1);

        // 从Redis中移除这些消息的过期时间（添加异常处理）
        try {
            mRedisService.batchRemoveMessageExpiry(ids);
        } catch (Exception e) {
            System.err.println("Redis连接失败，无法批量移除消息过期记录: " + e.getMessage());
        }
        return Result.success("批量已过期,共" + ids.size() + "条");
    }

}